package com.verisette.ncos.service.master.bizunit;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import org.corp.agi.common.exception.BusinessException;
import org.corp.agi.common.exception.ProcessException;
import org.corp.agi.service.bean.ProcessContext;
import org.corp.agi.service.bean.UserBean;
import org.corp.agi.service.bizunit.CommonBusinessUnit;
import com.verisette.ncos.common.ProjectConstant;
import com.verisette.ncos.persistence.domain.MasterUserGroup;

/**
 * 
 * {Description here}
 *
 * @author Ratapong Wongpiang (Earth)
 * @since Jul 1, 2010 4:48:57 PM
 * @see
 */
public class CreateUserGroupBU extends CommonBusinessUnit {

	private Logger logger = Logger.getLogger(CreateUserGroupBU.class);
	
	@Override
	public void execute(ProcessContext processContext) throws ProcessException {
		
		if(logger.isInfoEnabled()) logger.info( this.getClass().getSimpleName() + ": execute" );
		
		MasterUserGroup userGroup = (MasterUserGroup)processContext.getValueObject();
		UserBean user = processContext.getUserBean();
		Date currentDate = new Date();
		
		// Check same userGroupName
		logger.debug("1.Check same userGroupName.");
		MasterUserGroup criteriaUserGroup = new MasterUserGroup();
		criteriaUserGroup.setUsgName(userGroup.getUsgName());
		List<MasterUserGroup> foundList = (List<MasterUserGroup>)commonDAO.findByExample(criteriaUserGroup);
		
		if(foundList != null && foundList.size() != 0){
			// Same userName
			throw new BusinessException(ProjectConstant.MESSAGE_CODE_USG0001);
			
		}
		
		logger.debug("--> New UserGroup : " + userGroup.getUsgName());
		
		// Insert UserGroup into MASTER_USER_GROUP
		logger.debug("2.Insert UserGroup into MASTER_USER_GROUP."); 
		userGroup.setUsgCreatedDate(new Timestamp(currentDate.getTime()));
		userGroup.setUsgCreatedBy(user.getUsername());
		userGroup.setUsgLastUpdatedDate(new Timestamp(currentDate.getTime()));
		userGroup.setUsgLastUpdatedBy(user.getUsername());
		commonDAO.save(userGroup);
		commonDAO.flush();
		
		logger.debug("--> Insert Success !!!");
		logger.debug("--> UserGroupId : " + userGroup.getUsgId());
		
	}

}
